#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
YOLO数据集获取工具 - 启动脚本
提供程序启动、配置检查和错误处理功能
"""

import sys
import os
import traceback
from pathlib import Path


class YOLODatasetToolLauncher:
    """YOLO数据集获取工具启动器类"""
    
    def __init__(self):
        """初始化启动器"""
        self.version = "1.0.0"
        self.logger = None
        self.config_dir = os.path.expanduser("~/.yolo_dataset_tool")
        self.log_dir = os.path.join(self.config_dir, "logs")
        self.cache_dir = os.path.join(self.config_dir, "cache")
        self.downloads_dir = os.path.join(self.config_dir, "downloads")
        self.config_file = os.path.join(self.config_dir, "config.json")
        self.required_packages = [
            'PyQt5',
            'requests',
            'beautifulsoup4',
            'Pillow'
        ]

    def check_python_version(self):
        """检查Python版本是否符合要求"""
        if sys.version_info < (3, 7):
            print("错误: 需要Python 3.7或更高版本")
            print(f"当前版本: {sys.version}")
            return False
        return True

    def check_dependencies(self):
        """检查必要的依赖包是否安装"""
        missing_packages = []
        
        for package in self.required_packages:
            try:
                if package == 'beautifulsoup4':
                    import bs4  # 对应包的实际导入名
                elif package == 'Pillow':
                    import PIL  # 对应包的实际导入名
                else:
                    __import__(package)
            except ImportError:
                missing_packages.append(package)
        
        if missing_packages:
            print("错误: 缺少以下依赖包:")
            for package in missing_packages:
                print(f"  - {package}")
            print("\n请运行以下命令安装依赖:")
            print("pip install -r requirements.txt")
            return False
        
        return True

    def check_qt_environment(self):
        """检查Qt环境是否正常"""
        try:
            from PyQt5.QtWidgets import QApplication
            from PyQt5.QtWebEngineWidgets import QWebEngineView
            
            # 创建临时应用检查WebEngine组件
            app = QApplication([])
            web_view = QWebEngineView()
            web_view.deleteLater()  # 清理资源
            app.quit()
            
            return True
        except Exception as e:
            print(f"错误: Qt环境检查失败: {e}")
            print("请确保已正确安装PyQt5和PyQtWebEngine")
            return False

    def create_directories(self):
        """创建程序所需的目录结构"""
        directories = [
            self.config_dir,
            self.log_dir,
            self.cache_dir,
            self.downloads_dir
        ]
        
        for directory in directories:
            os.makedirs(directory, exist_ok=True)

    def setup_logging(self):
        """设置日志系统"""
        import logging
        
        log_file = os.path.join(self.log_dir, "yolo_dataset_tool.log")
        
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
        
        self.logger = logging.getLogger('YOLODatasetTool')
        return self.logger

    def check_config(self):
        """检查并创建默认配置文件"""
        if not os.path.exists(self.config_file):
            # 默认配置内容
            default_config = {
                "download_settings": {
                    "save_directory": os.path.expanduser("~/Downloads"),
                    "max_file_size": 1024,
                    "timeout": 300,
                    "retry_count": 3,
                    "chunk_size": 8,
                    "auto_rename": True
                },
                "image_search_settings": {
                    "max_images_per_page": 50,
                    "image_quality": "medium",
                    "download_format": "original",
                    "waterfall_columns": 4,
                    "max_pages": 100,
                    "pagination_buttons": 5,
                    "auto_load_more": False
                },
                "ui_settings": {
                    "window_width": 1200,
                    "window_height": 800,
                    "sidebar_width": 300,
                    "theme": "default"
                }
            }
            
            import json
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(default_config, f, indent=2, ensure_ascii=False)
            
            print(f"已创建默认配置文件: {self.config_file}")
            if self.logger:
                self.logger.info(f"已创建默认配置文件: {self.config_file}")

    def start_application(self):
        """启动主应用程序"""
        try:
            # 导入并运行主程序
            from main import main as main_app
            self.logger.info("启动主应用程序")
            main_app()
        except ImportError as e:
            self.logger.error(f"导入主程序模块失败: {e}")
            print(f"错误: 无法导入主程序模块: {e}")
            sys.exit(1)
        except Exception as e:
            self.logger.error(f"主程序运行错误: {e}")
            self.logger.error(traceback.format_exc())
            print(f"错误: 程序运行失败: {e}")
            print("详细信息请查看日志文件")
            sys.exit(1)

    def run(self):
        """运行启动流程"""
        print(f"YOLO数据集获取工具 v{self.version}")
        print("=" * 50)
        
        # 依次执行启动检查
        if not self.check_python_version():
            sys.exit(1)
        
        if not self.check_dependencies():
            sys.exit(1)
        
        if not self.check_qt_environment():
            sys.exit(1)
        
        # 初始化系统环境
        self.create_directories()
        self.setup_logging()
        self.logger.info("程序启动")
        
        self.check_config()
        
        # 启动应用
        try:
            self.start_application()
        finally:
            if self.logger:
                self.logger.info("程序退出")


if __name__ == "__main__":
    launcher = YOLODatasetToolLauncher()
    launcher.run()